document.addEventListener('DOMContentLoaded', function () {
    const chatMessages = document.getElementById('chat-messages');
    const userInput   = document.getElementById('user-input');
    const sendButton  = document.getElementById('send-button');
    const typingIndicator = document.getElementById('typing-indicator');
    
    // 语音控制按钮
    const playBtn = document.getElementById('play-btn');
    const pauseBtn = document.getElementById('pause-btn');
    const stopBtn = document.getElementById('stop-btn');
    
    const OLLAMA_API_URL = 'http://localhost:11434/api/generate';
    const MODEL_NAME     = 'qwen3:1.7b';
    
    // 语音合成相关变量
    let synthesis = window.speechSynthesis;
    let utterance = null;
    let currentSpeakingMessage = null;
    let defaultVoice = null;
    
    // 初始化语音合成
    function initSpeechSynthesis() {
        // 获取可用的语音
        function loadVoices() {
            const voices = synthesis.getVoices();
            
            // 优先选择中文语音
            defaultVoice = voices.find(voice => voice.lang.includes('zh')) || 
                           voices.find(voice => voice.lang.includes('cmn')) || 
                           voices[0];
        }
        
        loadVoices();
        
        // 语音列表可能异步加载
        if (speechSynthesis.onvoiceschanged !== undefined) {
            speechSynthesis.onvoiceschanged = loadVoices;
        }
    }
    
    // 文本转语音
    function speakText(text, messageElement) {
        if (synthesis.speaking) {
            synthesis.cancel();
        }
        
        utterance = new SpeechSynthesisUtterance(text);
        
        // 使用默认语音
        if (defaultVoice) {
            utterance.voice = defaultVoice;
        }
        
        // 添加语音播放指示器
        if (currentSpeakingMessage) {
            currentSpeakingMessage.classList.remove('speaking');
        }
        
        messageElement.classList.add('speaking');
        currentSpeakingMessage = messageElement;
        
        // 更新按钮状态
        playBtn.disabled = true;
        pauseBtn.disabled = false;
        stopBtn.disabled = false;
        
        utterance.onend = function() {
            messageElement.classList.remove('speaking');
            playBtn.disabled = false;
            pauseBtn.disabled = true;
            stopBtn.disabled = true;
            currentSpeakingMessage = null;
        };
        
        utterance.onerror = function() {
            messageElement.classList.remove('speaking');
            playBtn.disabled = false;
            pauseBtn.disabled = true;
            stopBtn.disabled = true;
            currentSpeakingMessage = null;
        };
        
        synthesis.speak(utterance);
    }
    
    // 添加消息到聊天窗口
    function addMessage(text, isUser) {
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message', isUser ? 'user-message' : 'bot-message');
        
        const contentDiv = document.createElement('div');
        contentDiv.classList.add('message-content');
        contentDiv.textContent = text;
        
        messageDiv.appendChild(contentDiv);
        
        // 如果不是用户消息，添加朗读按钮
        if (!isUser) {
            const ttsBtn = document.createElement('button');
            ttsBtn.classList.add('tts-btn');
            ttsBtn.title = "朗读此消息";
            ttsBtn.textContent = "🔊";
            ttsBtn.addEventListener('click', function() {
                speakText(text, messageDiv);
            });
            messageDiv.appendChild(ttsBtn);
        }
        
        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
        
        return messageDiv;
    }

    function showTypingIndicator() {
        typingIndicator.style.display = 'block';
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
    function hideTypingIndicator() {
        typingIndicator.style.display = 'none';
    }
    
    function removeThinkTags(response) {
        // 使用正则表达式移除<think>标签及其内容
        return response.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
    }

    async function sendMessageToOllama(message) {
        showTypingIndicator();
        sendButton.disabled = true;

        try {
            const res = await fetch(OLLAMA_API_URL, {
                method : 'POST',
                headers: { 'Content-Type': 'application/json' },
                body   : JSON.stringify({ model: MODEL_NAME, prompt: message, stream: false })
            });
            if (!res.ok) throw new Error(`HTTP错误: ${res.status}`);

            const data = await res.json();
            // 移除响应中的<think>标签及其内容
            const cleanResponse = removeThinkTags(data.response);

            hideTypingIndicator();
            const messageElement = addMessage(cleanResponse, false);
            
            // 自动朗读最新回复
            speakText(cleanResponse, messageElement);

        } catch (err) {
            console.error('调用Ollama API时出错:', err);
            hideTypingIndicator();
            
            const isCors = err.message.includes('Failed to fetch') || err.message.includes('CORS');
            addMessage(
                isCors
                    ? '错误: 浏览器阻止了跨域请求。请尝试使用Edge浏览器并启用"allow-insecure-localhost"选项，或使用Python启动本地服务器。'
                    : '错误: ' + err.message,
                false
            );
        } finally {
            sendButton.disabled = false;
            userInput.focus();
        }
    }

    function handleSendMessage() {
        const msg = userInput.value.trim();
        if (msg) {
            addMessage(msg, true);
            userInput.value = '';
            sendMessageToOllama(msg);
        }
    }

    // 事件监听
    sendButton.addEventListener('click', handleSendMessage);
    userInput.addEventListener('keypress', e => {
        if (e.key === 'Enter') handleSendMessage();
    });
    userInput.focus();
    
    // 语音控制事件
    playBtn.addEventListener('click', () => {
        if (synthesis.paused) {
            synthesis.resume();
            playBtn.disabled = true;
            pauseBtn.disabled = false;
        }
    });
    
    pauseBtn.addEventListener('click', () => {
        if (synthesis.speaking && !synthesis.paused) {
            synthesis.pause();
            pauseBtn.disabled = true;
            playBtn.disabled = false;
        }
    });
    
    stopBtn.addEventListener('click', () => {
        if (synthesis.speaking) {
            synthesis.cancel();
            playBtn.disabled = false;
            pauseBtn.disabled = true;
            stopBtn.disabled = true;
            
            if (currentSpeakingMessage) {
                currentSpeakingMessage.classList.remove('speaking');
                currentSpeakingMessage = null;
            }
        }
    });
    
    // 初始化语音合成
    initSpeechSynthesis();

    /* ---------- 初始连接测试 ---------- */
    (async function testConnection() {
        try {
            const res = await fetch('http://localhost:11434/api/tags');
            if (!res.ok) throw new Error('无法访问Ollama API');

            const data = await res.json();
            console.log('检测到的模型:', data.models);
        } catch (err) {
            console.error('连接测试失败:', err);
            const isCors = err.message.includes('Failed to fetch') || err.message.includes('CORS');
            if (isCors) {
                addMessage('注意: 检测到Ollama服务正在运行，但浏览器安全策略阻止了直接访问。请尝试上述解决方案。', false);
            } else {
                addMessage('错误: ' + err.message, false);
            }
        }
    })();
});